package me.leiusual.sharing.ui.base

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.alipay.sdk.app.PayTask
import com.google.gson.JsonObject
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import dagger.android.support.DaggerFragment
import kotlinx.coroutines.*
import me.leiusual.sharing.util.extension.toast
import me.leiusual.sharing.util.tool.Constants
import timber.log.Timber

/**
 * Create by malei on 2018/6/27
 */
abstract class AbstractFragment : DaggerFragment() {

  abstract val abstractViewModel: AbstractViewModel

  // 微信支付API
  private val api: IWXAPI by lazy {
    WXAPIFactory.createWXAPI(requireContext().applicationContext, Constants.WXPAY_APP_ID)
  }

  private var payJob: Job? = null

  private val broadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
      Timber.v("intent = %s", intent)

      val errCode = intent.getIntExtra("errCode", 0)
      val errStr = intent.getStringExtra("errStr")

      when (errCode) {
        0 -> {
          toast("支付成功")
          abstractViewModel.paySuccess()
        }
        -1 -> {
          toast(errStr)
        }
        -2 -> {
          toast("取消支付")
        }
      }
    }
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // 注册微信支付结果通知广播
    val intentFilter = IntentFilter(Constants.ACTION_WXPAY_RESULT)
    LocalBroadcastManager.getInstance(requireContext()).registerReceiver(broadcastReceiver, intentFilter)
  }

  override fun onDestroyView() {
    super.onDestroyView()

    // 注销微信支付结果通知广播
    LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(broadcastReceiver)
  }

  override fun onDestroy() {
    super.onDestroy()
    payJob?.cancel()
  }

  /**
   * 微信支付
   */
  fun doPayByWeChat(orderInfo: JsonObject) {

    val request = PayReq()
    request.appId = orderInfo.get("appid").asString
    request.partnerId = orderInfo.get("partnerid").asString
    request.prepayId = orderInfo.get("prepayid").asString
    request.packageValue = orderInfo.get("package").asString
    request.nonceStr = orderInfo.get("noncestr").asString
    request.timeStamp = orderInfo.get("timestamp").asString
    request.sign = orderInfo.get("sign").asString
    api.sendReq(request)
  }

  /**
   * 支付宝支付
   */
  fun doPayByAlipay(orderInfo: JsonObject) {
    payJob?.cancel()
    payJob = GlobalScope.launch(Dispatchers.Main) {

      val result = withContext(Dispatchers.IO) {
        val payTask = PayTask(requireActivity())
        val result = payTask.payV2(orderInfo.get("data").asString, true)
        Timber.v("result = %s", result)
        result.getOrElse("resultStatus") { "-1" }
      }

      if (result == "9000") {
        toast("支付成功")
        abstractViewModel.paySuccess()
      } else {
        toast("支付失败：$result")
      }
    }
  }
}